package your.packag;

import java.io.IOException;
import DAO.*;
import DTO.AccountChartDTO;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;

import android.R.color;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import com.java4less.rchart.Chart;
import com.java4less.rchart.ChartAdapter;
import com.java4less.rchart.ChartListener;
import com.java4less.rchart.ChartAdapter;
import com.java4less.rchart.ChartListener;
import com.java4less.rchart.ChartLoader;
import com.java4less.rchart.android.ChartPanel;
import com.java4less.rchart.gc.android.ChartAndroidImage;

public class ReportActivity extends Activity {
	private static final String TAG = "j4lchart";
	ChartLoader cha=new ChartLoader();
	ChartPanel chartPanel;
	List<AccountChartDTO> account;
	List<String> Color =  new ArrayList<String>(); 
	// create chart listener 
	ChartAdapter chartAdapter=new ChartAdapter() {
					public void chartEvent(Chart c,int type) {
						
						Log.e(ChartPanel.TAG,"Chart event "+ type);
						
						if (type==ChartListener.EVENT_CHART_CLICKED) {
							
						}
						
						if (type==ChartListener.EVENT_POINT_CLICKED) {
							Log.e(ChartPanel.TAG,"Point clicked "+ c.selectedSeriePoint);
						}						

						// rebuild chart with new data
						if (type==ChartListener.EVENT_BEFORE_UPDATE) {
							// // get a new random value between 0 and 40 and update 3 of the values in the serie
							int newValue=(int) (System.currentTimeMillis() % 40); 
							c.plotters[0].getSerie(0).replaceYValueAt(1,newValue);
							c.plotters[0].getSerie(0).replaceYValueAt(2,newValue+10);
							c.plotters[0].getSerie(0).replaceYValueAt(3,newValue-10);							

							// do not allow the chart to be rebuilt from the original parameters
							c.autoRebuild=false;
							
						}						
						
					}
				};	
					
				
				// create chart listener for the drill down chart
				ChartAdapter chartAdapterRealtime=new ChartAdapter() {
									public void chartEvent(Chart c,int type) {
										Log.e(ChartPanel.TAG,"Chart event "+ type);						
										// load subchart
										if (type==ChartListener.EVENT_BEFORE_UPDATE) createRealtimedata(cha);
									}
								};	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        ;
       // setContentView(R.layout.report);
        cha=new ChartLoader();
		// this is to be able to load the images
	    ChartAndroidImage.assets=getAssets();
	    super.onCreate(savedInstanceState);
	     Color.add("RED");
	     Color.add("ORANGE");
	     Color.add("YELLOW");
	     Color.add("GREEN");
	     Color.add("BLUE");

		
      //org.jsoup.nodes.Document doc = Jsoup.connect("http://smartwebvina.com/smartlive/").get();
      

          
	    chartPanel = new ChartPanel(this);
	    
        try {
			//chartPanel.setChart(loadFromAsset("linechart3D.txt"));
        	chartPanel.setChart(this.createDefaultChart());
        	
		} catch (Exception e) {
			Log.e(ChartPanel.TAG,"Could not lod chart from file.",e);
		}
        
        setContentView(chartPanel);    
	    
	}
	  public Chart loadFromAsset(String name) throws IOException {
      	
          InputStream is = getAssets().open(name);        	
          	
          cha.loadFromFile(is, true);
          
			Log.i(ChartPanel.TAG,"Building chart ...");

			Chart c=cha.build(false,false);	
			c.setWidth(300);
			c.setHeight(300);
			
			// scroll example
			if (name.equals("linechart.txt"))  {
			c.virtualWidth=600;
			c.withScroll=true;
			c.repaintAlways=false;			
			}
			

			// set listener for realtime update example
			//if (name.equals("barChart3D.txt")) 
				c.addChartListener(chartAdapter);				
			if (name.equals("realtime.txt")) c.addChartListener(chartAdapterRealtime);
						

			
						
			
			// real time update example, start update thread
			if ((name.equals("barChart3D.txt")) || (name.equals("realtime.txt")))  c.startUpdater();				
			
			Log.i(ChartPanel.TAG,"Build ok");	
			
			c.activateSelection=true;
			
			return c;            
      }
	  public Chart createDefaultChart() throws ParseException, IOException {
		  HttpGet httpGet = new HttpGet("http://smartwebvina.com/smartlive/index.php?option=com_mymonney");
		  HttpResponse response = LoginActivity.postClient.execute(httpGet);
		  	HttpEntity httpEntity = response.getEntity();
	        String xml = EntityUtils.toString(httpEntity);
	        org.jsoup.nodes.Document doc = Jsoup.parse(xml);
	      //org.jsoup.nodes.Document doc = Jsoup.connect("http://smartwebvina.com/smartlive/").get();
	      

	      
	        MyData data = new MyData();
	        account =data.readAccountChart(doc);
	        
			System.out.println("Creating loader ...");

			ChartLoader cha=new ChartLoader();			
			cha.clearParams();	
		
			cha.setParameter("TITLECHART","Account Report");
			cha.setParameter("LEGEND_FILL","RED");
			cha.setParameter("LEGEND_VERTICAL","TRUE");
			cha.setParameter("SERIE_1", "Pie");
			cha.setParameter("SERIE_TYPE_1", "PIE");
			cha.setParameter("SERIE_FONT_1", "ARIAL|BOLD|12");
			cha.setParameter("SERIE_DATA_1", "" + ParseValue());
			for(int i =0 ;i < account.size();i++)
			{
				cha.setParameter("PIE_NAME_" + (i+1), "" + account.get(i).type());
				
			}
			for(int i =0 ;i < account.size();i++)
			{
				cha.setParameter("PIE_STYLE_" +(i+1), "" + Color.get(i));
			}
			
			
			

			cha.setParameter("PIECHART_RADIUS", "0.8");
			cha.setParameter("PIECHART_3D", "TRUE");
			cha.setParameter("PIE_LABEL_FORMAT", "#VALUE#");
			cha.setParameter("SERIE_LABELS_1", "" + ParseSerial());
			cha.setParameter("SERIE_TOGETHER_1","" + ParseTogether()	);
			cha.setParameter("LEGEND_POSITION", "TOP");
			cha.setParameter("CHART_BORDER", "0.05|0x0|NORMAL");
			cha.setParameter("CHART_FILL", "WHITE");
			//cha.setParameter("BACK_IMAGE", "BLACK");
			Chart c=cha.build(false,false);	
			c.setWidth(480);
			c.setHeight(800);

			
			Log.i(ChartPanel.TAG,"Build ok");			
			
			return c;


		}
	  public String ParseValue()
	  {
		  String temp ="";
		  for(int i =0 ;i< account.size() ;i ++)
		  {
			  temp+= account.get(i).value();
			  if(i<account.size()-1)
			  temp += "|";
		  }
		  return temp;
	  }
	  
	  public String ParseSerial()
	  {
		  String temp ="";
		  for(int i =0 ;i< account.size() ;i ++)
		  {
			  temp+= account.get(i).type();
			  if(i<account.size()-1)
			  temp += "|";
		  }
		  return temp;
	  }
	  
	  public String ParseTogether()
	  {
		  String temp ="";
		  for(int i =0 ;i< account.size() ;i ++)
		  {
			  temp+= "true";
			  if(i<account.size()-1)
			  temp += "|";
		  }
		  return temp;
	  }
	private void createRealtimedata(ChartLoader loader) {
		//	create chart

		//	set initial value of the X Axis based on the time
		java.util.Date now=java.util.Calendar.getInstance().getTime();
		java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("dd/MM/yy hh:mm:ss");

		loader.setParameter("XAXIS_INITIAL_DATE",formatter.format(now));


		//	create random data based on the time
		java.util.Calendar cal=java.util.Calendar.getInstance();
		String data1="";
		String data2="";
		for (int i=0;i<9;i++) {		
			cal.add(java.util.Calendar.SECOND,-2);
			if (data1.length()>0) data1="|" + data1;
			data1=""+cal.get(java.util.Calendar.SECOND)+ data1;
			if (data2.length()>0) data2="|" + data2;
			data2=""+(cal.get(java.util.Calendar.SECOND)/6)+ data2;		
		}

		loader.setParameter("SERIE_DATA_1",data1);
		loader.setParameter("SERIE_DATA_2",data2);
		

   }    

}
